package com.gt.utils;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;

import javax.mail.internet.MimeMessage;
import java.io.File;

/**
 * 发送邮件类，由于服务器关闭25端口，且不支持ssl，弃用，修改为EmailUtil2
 */
public class EmailUtil {
    private static Logger logger = Logger.getLogger(EmailUtil.class);
    /**
     * 发送普通邮件
     * @param toArr     收件人数组
     * @param subject   邮件主题
     * @param content   邮件内容
     * @throws Exception
     */
    public static void sendSimpleEmail(String sender, String toArr[], String subject, String content, JavaMailSender javaMailSender) throws Exception{
        logger.info("发送普通邮件:收件人:"+ StringUtils.join(toArr,"、")+",主题:"+subject+"，内容："+content);
        SimpleMailMessage msg = new SimpleMailMessage();
        msg.setFrom(sender);
        msg.setTo(toArr);
        msg.setSubject(subject);
        msg.setText(content);
        javaMailSender.send(msg);
    }

    /**
     * 发送html邮件
     * @param toArr     收件人数组
     * @param subject   主题
     * @param content   html内容（StringBuilder）
     * @throws Exception
     */
    public static void sendHtmlEmail(String sender, String toArr[], String subject, StringBuilder content, JavaMailSender javaMailSender) throws Exception{
        logger.info("发送html邮件:收件人:"+ StringUtils.join(toArr,"、")+",主题:"+subject+"，内容："+content);
        MimeMessage msg = null;
        try{
            msg = javaMailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(msg, true);
            helper.setFrom(sender);
            helper.setTo(toArr);
            helper.setSubject(subject);
            helper.setText(content.toString(), true);
            FileSystemResource file = new FileSystemResource(new File("src/main/resources/static/css/assets/img/logo_red.png"));
            helper.addInline("picture",file);
            javaMailSender.send(msg);
        }catch (Exception e){
            logger.error("发送html邮寄异常", e);
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        String arr[] = {"张三","李四","王五"};
        System.out.println(arr);
        System.out.println(StringUtils.join(arr,"、"));
    }
}
